package com.example.software.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

// import org.apache.shiro.authz.annotation.RequiresPermissions;
import cn.hutool.core.bean.BeanUtil;
import com.example.software.constant.JwtClaimsConstant;
import com.example.software.context.BaseContext;
import com.example.software.dto.doctorLoginDTO;
import com.example.software.entity.*;
import com.example.software.properties.JwtProperties;
import com.example.software.service.ApplyService;
import com.example.software.service.WorkdayService;
import com.example.software.utils.JwtUtil;
import com.example.software.vo.loginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import com.example.software.service.AdminService;
import com.example.software.utils.PageUtils;
import com.example.software.utils.R;



/**
 * 
 *
 * @author wxy
 * @email wxy9496099@163.com
 * @date 2024-10-28 10:54:38
 */
@RestController
@Slf4j
@Api(tags = "管理员相关接口")
@RequestMapping("software/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;

    @Autowired
    private ApplyService applyService;

    @Autowired
    private WorkdayService workdayService;

    @Autowired
    private JwtProperties jwtProperties;

    //查看医院收益


    @PutMapping("/apply")
    @ApiOperation(value = "审批医生排班申请")
    // @RequiresPermissions("software:apply:update")
    public R update(@RequestBody ApplyEntity apply){

        WorkdayEntity workday = new WorkdayEntity();

        workday.setId(apply.getWorkdayId());


        if (apply.getState()==1){
            if (apply.getRequest()==1){
                workday.setState(1);
            }else if (apply.getRequest()==0){
                workday.setState(2);
            }
            log.info("同意申请");

            workdayService.updateById(workday);
        }
//        if (apply.getState()==2){
//            workday.setState(1);
//            log.info("拒绝申请");
//        }


        applyService.updateById(apply);

        return R.ok();
    }

    @PostMapping("/login")
    @ApiOperation(value = "管理员登录")
    public Result<loginVO> login(@RequestBody doctorLoginDTO doctorDTO){

        log.info("登录：{}", doctorDTO);

        AdminEntity adminEntity = adminService.login(doctorDTO);
        Map<String, Object> claims = new HashMap<>();

        claims.put(JwtClaimsConstant.doctor_ID, adminEntity.getId());
        log.info("管理员登录");

//        if(doctorEntity.getAuth() == 0){
//            Long store_id = storeService.getByEmployeeId(employee.getId());   //新增v1
//            //登录成功后，生成jwt令牌
//            System.out.println("store_id2 "+store_id);
//            claims.put(JwtClaimsConstant.EMP_ID, employee.getId());
//            claims.put("store_id", store_id);  //新增v1
//            log.info("员工登录");
//        }else{
//            //如果是管理员就不用保存他对应的店铺id了
//            //登录成功后，生成jwt令牌
//            claims.put(JwtClaimsConstant.EMP_ID, employee.getId());
//            log.info("管理员登录");
//        }

        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        loginVO adminVO = com.example.software.vo.loginVO.builder()
                .id(adminEntity.getId())
                .username(adminEntity.getUsername())
                .name(adminEntity.getName())
                .token(token)
                .build();

        return  Result.success(adminVO);
    }

//    /**
//     * 列表
//     */
//    @RequestMapping("/list")
////    @RequiresPermissions("software:admin:list")
//    public R list(@RequestParam Map<String, Object> params){
//
//        PageUtils page = adminService.queryPage(params);
//
//        return R.ok().put("page", page);
//    }
//
//
    /**
     * 信息
     */
    @GetMapping("/info")
    @ApiOperation("获取当前用户信息")
    // @RequiresPermissions("software:admin:info")
    public Result<AdminEntity> info(){
        BaseContext.getCurrentId();
		AdminEntity admin = adminService.getById(BaseContext.getCurrentId());

        return Result.success(admin);
    }


    @GetMapping ("/parseAdmin")
    @CrossOrigin
    @ApiOperation("解析token获取当前用户信息")
    public Result<AdminEntity> parseToken(String token){

        log.info("解析token获取当前用户信息：{}",token);
        Map<String, Object> claims = null;
        //解析token
        try {
            claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("登录失效，请重新登录");
        }

        if (claims == null) {
            return Result.error("登录失效，请重新登录");
        }

        //获取用户id
        Long userId = Long.valueOf(claims.get(JwtClaimsConstant.doctor_ID).toString());

        //根据用户id查询用户信息
        AdminEntity adminEntity = adminService.getById(userId);

//        if(doctorEntity.getAuth() == 1){
//
//            return Result.success(employeeVO);
//        }else if(employee.getAuth() == 0){
//            Long store_id = storeService.getByEmployeeId(employee.getId());   //新增v1
//            Store store = storeService.getById(store_id);
//            StoreVO storeVO = new StoreVO();
//
//            BeanUtil.copyProperties(store,storeVO);
//            employeeVO.setStoreVO(storeVO);
//            return Result.success(employeeVO);
//        }

        return Result.success(adminEntity);
    }


//
//    /**
//     * 保存
//     */
//    @RequestMapping("/save")
//    // @RequiresPermissions("software:admin:save")
//    public R save(@RequestBody AdminEntity admin){
//		adminService.save(admin);
//
//        return R.ok();
//    }
//



    /**
     * 修改
     */
    @PutMapping("/update")
    @ApiOperation(value = "修改管理员信息")
    // @RequiresPermissions("software:admin:update")
    public R update(@RequestBody AdminEntity admin){


//        if (admin.getPassword() != null && !admin.getPassword().isEmpty()){
//            admin.setPassword(DigestUtils.md5DigestAsHex(admin.getPassword().getBytes()));
//        }
        AdminEntity adminEntity = new AdminEntity();
        adminEntity.setId(admin.getId());
        if (admin.getPassword() != null && !admin.getPassword().isEmpty()){
            adminEntity.setPassword(DigestUtils.md5DigestAsHex(admin.getPassword().getBytes()));
        }
        if (admin.getName() != null && !admin.getName().isEmpty()){
            adminEntity.setName(admin.getName());
        }
        if (admin.getUsername() != null && !admin.getUsername().isEmpty()){
            adminEntity.setUsername(admin.getUsername());
        }


		adminService.updateById(adminEntity);

        return R.ok();

    }
//
//    /**
//     * 删除
//     */
//    @RequestMapping("/delete")
//    // @RequiresPermissions("software:admin:delete")
//    public R delete(@RequestBody String[] accounts){
//		adminService.removeByIds(Arrays.asList(accounts));
//
//        return R.ok();
//    }

}
